package cn.tedu.ximart.server.service.impl;


import cn.tedu.ximart.server.ex.ServiceException;
import cn.tedu.ximart.server.mapper.BrandMapper;
import cn.tedu.ximart.server.pojo.dto.BrandAddNewDTO;
import cn.tedu.ximart.server.pojo.entity.Brand;
import cn.tedu.ximart.server.pojo.vo.BrandListItemVO;
import cn.tedu.ximart.server.repo.IBrandRepository;
import cn.tedu.ximart.server.service.IBrandService;
import cn.tedu.ximart.server.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class BrandServiceImpl implements IBrandService {

    @Autowired
    private IBrandRepository brandRepository;
    @Autowired
    private BrandMapper brandMapper;

    private BrandServiceImpl(){
        System.out.println("BrandServiceImpl的构造方法被调用了");
    }


    @Override
    public void addNew(BrandAddNewDTO brandAddNewDTO) {
        log.debug("准备开始处理增加品牌的业务，参数：{}",brandAddNewDTO);

        String name = brandAddNewDTO.getName();
        int count = brandMapper.countByName(name);
        if(count>0){
            String message = "增加品牌失败，品牌名称【"+name+"】已经被占用";
            throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }
        //创建实例对象（Mapper的方法的参数是实体类型）
        Brand brand = new Brand();

        //将当前方法参数的值复制到Brand实体类型的对象中
        BeanUtils.copyProperties(brandAddNewDTO,brand);
        brand.setSales(0);
        brand.setPositiveCommentCount(0);
        brand.setCommentCount(0);
        brand.setEnable(1);


        //将品牌数据写入到数据库中
        int rows = brandMapper.insert(brand);
        if(rows!=1){
            String message = "添加品牌失败，服务器繁忙，请稍后再尝试";
            log.error(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }
    }

    @Override
    public void deleteById(Long id) {
        if(brandMapper.selectById(id)==null){
            String message = "删除品牌失败，尝试删除的数据（id="+id+"）不存在";
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }
        int rows = brandMapper.deleteById(id);
        if(rows!=1){
            String message = "删除品牌失败，服务器繁忙，请稍后再尝试";
            log.error(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }
    }

    @Override
    public List<BrandListItemVO> list() {
        log.debug("开始处理查询品牌列表的业务");
        return brandMapper.list();
    }


}
